package com.gateway.config.gay.nacos;

import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author Huangkai
 */
@Slf4j
@Component
public class NacosServiceConfig {

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String serviceAddr;

    @Value("${spring.cloud.nacos.discovery.namespace}")
    private String namespace;

    @Value("${spring.cloud.nacos.username}")
    private String username;

    @Value("${spring.cloud.nacos.password}")
    private String password;

    @Autowired
    NacosServiceManager nacosServiceManager;

    public  List<Instance> configService(String serviceName) {
        List<Instance> instances = new ArrayList<>();
        try{
            NamingService nacosNamingService = nacosServiceManager.getNamingService(getProperties());
            instances = nacosNamingService.getAllInstances(serviceName);
            if(!CollectionUtils.isEmpty(instances)){
                return instances;
            }
        }catch (NacosException e){
            e.printStackTrace();
        }
        return instances;
    }

    /**
     * 获取配置
     * @return
     */
    public ConfigService getConfigService() throws NacosException {
        ConfigService configService = NacosFactory.createConfigService(getProperties());
        return configService;
    }

    public Properties getProperties(){
        Properties properties = new Properties();
        // nacos服务器地址
        properties.put(PropertyKeyConst.SERVER_ADDR, serviceAddr);
        // 配置中心的命名空间id
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);
        return properties;
    }
}
